package com.moyuxi.sound_of_the_forest.viewModel

import android.content.Context
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.annotation.RequiresApi
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.moyuxi.sound_of_the_forest.MediaPlayerHelper
import com.moyuxi.sound_of_the_forest.entity.LocalMusicBean
import com.moyuxi.sound_of_the_forest.sql.MusicListDataBase


class MainViewModel(var context: Context) : ViewModel() {

//    private lateinit var context: Context


    /**
     * 音乐播放器助手
     */
    private val mediaPH = MediaPlayerHelper.instance


    private val mData = MutableLiveData<List<LocalMusicBean>>()

    /**
     * 总数据
     */
    val data: LiveData<List<LocalMusicBean>>
        get() = mData

    /**
     * 正在播放的音乐条目
     */
    val playMusicBean = mediaPH.playMusicBean

    /**
     * 播放进度
     */
    val playingProgress = mediaPH.playingProgress

    /**
     * 播放状态
     */
    val isPlaying = mediaPH.isPlaying

    /**
     * 播放列表
     */
    val playMusicList = mediaPH.playMusicList


    private val _targetSong = MutableLiveData<MutableList<LocalMusicBean>>()

    /**
     * 搜索歌曲结果
     */
    val targetSong: LiveData<MutableList<LocalMusicBean>>
        get() = _targetSong

    /**
     * 添加歌曲至播放列表
     */
    fun addSongToPlayingList(song: LocalMusicBean) {
        mediaPH.addSongToPlaylist(song)
    }

    /**
     * 从播放列表中移出歌曲
     */
    fun removeSongInPlayingList(bean: LocalMusicBean) {
        mediaPH.removeBeanOnList(bean)
    }

    /**
     * 从歌曲列表中移出歌曲
     */
    fun removeSongInDataList(bean: LocalMusicBean) {
        mData.value = mData.value?.minus(bean)
        MusicListDataBase.getDB().getMusicListDao().deleteUser(bean)
    }


    /**
     * 搜素歌曲
     */
    fun searchSong(targetSong: String = "") {
        if (targetSong != "") mData.value?.let {
            val sr: MutableList<LocalMusicBean> = ArrayList()
            for (bean in it) if (targetSong in bean.singer || targetSong in bean.name) sr += bean
            _targetSong.value = sr
        }
        else _targetSong.value = mData.value?.toMutableList()
    }

    /**
     * 加载本地音乐文件
     */
    @RequiresApi(Build.VERSION_CODES.Q)
    fun loadLocalMusicData(context: Context) {
        this.context = context
        // 获取内容解析器查询外部内容URI 音乐的游标
        val cursor = context.contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            null,
            null,
            null,
            MediaStore.Audio.Media.IS_MUSIC
        )
        if (cursor != null) {
            val list = ArrayList<LocalMusicBean>()
            MusicListDataBase.init(context)
            MusicListDataBase.getDB().clearAllTables()
            while (cursor.moveToNext()) {
                //歌曲大小
                val size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE))
                if (size > 1000 * 800) {
                    list.add(
                        LocalMusicBean(
                            cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)),
                            cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)),
                            cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)),
                            cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)),
                            cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)),
                            cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)),
                            size,
                            getAlbumArt(
                                cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)),
                                context
                            )
                        )
                    )
                }
            }
            cursor.close()
            mData.value = list
            MusicListDataBase.getDB().getMusicListDao().insertUsers(*list.toTypedArray())
        }
    }

    /**
     * 加载数据库中的歌曲数据
     */
    fun loadLocalMusicByDatabase(context: Context) {
        MusicListDataBase.init(context)
        MusicListDataBase.getDB().getMusicListDao().getAllBean()
            ?.let { mData.value = it.toMutableList() }
    }

    /**
     * 填充全部数据至播放列表
     */
    fun pushAllListToMediaPlayerData(list: List<LocalMusicBean>) {
        if (list.size < 1) return
        mediaPH.setPlayMusicList(list)
    }

    /**
     * 填充全部数据至播放列表并播放第一首
     */
    fun pushAllListToPlayerDataAndPlaying(list:List<LocalMusicBean>) {
        if (list.isEmpty()) return
        mediaPH.setPlayMusicList(list)
        mediaPH.playMusicInBean(list[0])
    }

    /**
     * 获取专辑封面
     */
    @RequiresApi(Build.VERSION_CODES.Q)
    private fun getAlbumArt(albumId: Long, context: Context): String? {
        val uri = "content://media/external/audio/albums/${albumId}"
        var albumArt: String? = null
        val albumCursor = context.contentResolver.query(
            Uri.parse(uri), arrayOf("album_art"), null, null, null
        )
        if ((albumCursor!!.count > 0) && (albumCursor.columnCount > 0)) {
            albumCursor.moveToNext()
            albumArt = albumCursor.getString(0)
        }
        albumCursor.close()
//        val cursor = context.contentResolver.query(
//            MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
//            arrayOf(MediaStore.Audio.Albums.ALBUM_ID,MediaStore.Audio.Albums.ALBUM_ART),
//            MediaStore.Audio.Albums._ID + "=?",
//            arrayOf(albumId.toString()),
//            null
//        )
//        var albumArt: String? = null
//        if (cursor != null && (cursor.count > 0)) {
//            cursor.moveToFirst()
//            albumArt =
//                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM_ART))
//            cursor.close()
//        }
        return albumArt
    }

    /**
     * 播放一首音乐
     */
    fun playMusicInBean(bean: LocalMusicBean) {
        mediaPH.playMusicInBean(bean)
    }

    /**
     * 上一首
     */
    fun playLastMusic() {
        mediaPH.playLastMusic()
    }

    /**
     * 播放/暂停
     */
    fun playCurrentMusic() {
        mediaPH.playCurrentMusic()
    }

    /**
     * 下一首
     */
    fun playNextMusic() {
        mediaPH.playNextMusic()
    }

    /**
     * 结束音乐播放器
     */
    fun stopMusic() {
        mediaPH.stopMusic()
    }
}
